package com.qianchang.microfinance.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.DialogFragment;

import com.qianchang.microfinance.bean.AboutInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.dm.library.download.listener.impl.UIProgressListener;
import com.dm.library.download.utils.DownLoadUtils;
import com.dm.library.utils.FormatUtil;

import java.io.File;

/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述: 版本更新管理类
 * 修 改 人: jiaohongyun
 * 修改时间: 2017/2/22
 */
public class AppUpdateManager {

    private static final int CODE_REQUEST = 101;

    private ActionInterFace actionInterFace;
    private Activity mContext;

    public static AppUpdateManager getNewInstance(Activity context) {
        return new AppUpdateManager(context, null);
    }

    public static AppUpdateManager getNewInstance(Activity context, ActionInterFace actionInterFace) {
        return new AppUpdateManager(context, actionInterFace);
    }

    private AppUpdateManager(Activity context, ActionInterFace actionInterFace) {
        mContext = context;
        this.actionInterFace = actionInterFace;
    }

//    public void checkVersion(String url, Map<String, String> params) {
//        DMOKHttpUtils.getInstance().post(mContext, url, params, new RequestCallBack<Ab>() {
//            @Override
//            public void onSuccess(JsonResult<UpdateInfo> response) {
//                String code = response.getCode();
//                if (DMConstant.Code.CODE_OK.equals(code)) {
//                    UpdateInfo updateBean = response.getObject();
//                    if (updateBean != null && needUpdate(updateBean)) {
//                        //界面显示有新的版本
//                        if (mustUpdate(updateBean)) {
//                            actionInterFace.showMustUpdate(updateBean);
//                        } else {
//                            actionInterFace.showNewVersion(updateBean);
//                        }
//                    } else {
//                        actionInterFace.showLocalVersion();
//                    }
//                } else {
//                    String description = response.getDescription();
//                    actionInterFace.showRequestError(code, description);
//                }
//            }
//
//            @Override
//            public void onFailure(String msg) {
//                actionInterFace.onFailure(msg);
//            }
//
//            @Override
//            public void onConnectFailure(String msg) {
//                actionInterFace.onConnectFailure(msg);
//            }
//        });
//    }

//    /**
//     * 是否强制更新
//     *
//     * @param updateBean
//     * @return
//     */
//    private boolean mustUpdate(UpdateInfo updateBean) {
//        return "0".equals(updateBean.getMandatoryUpdate());
//    }

    /**
     * 是否需要更新
     *
     * @return
     */
    public static boolean needUpdate(AboutInfo updateBean) {
        if (null == updateBean) {
            return false;
        }
        // 获取当前APP版本号
        String currentVersion = getCurrentVersion();

        //如果版本格式不是1.1.1这种的，则不用更新
        if (!FormatUtil.isNumberAndPoint(updateBean.getVersion())) {
            return false;
        }

        String newVersion = updateBean.getVersion().replace(".", "");
        currentVersion = currentVersion.replace(".", "");
        if (newVersion.length() > currentVersion.length()) {
            StringBuilder temp = new StringBuilder(currentVersion);
            for (int i = 0; i < newVersion.length() - currentVersion.length(); i++) {
                temp.append("0");
            }
            currentVersion = temp.toString();
        } else if (newVersion.length() < currentVersion.length()) {
            StringBuilder temp = new StringBuilder(newVersion);
            for (int i = 0; i < currentVersion.length() - newVersion.length(); i++) {
                temp.append("0");
            }
            newVersion = temp.toString();
        }

        // 比较版本号看是否需要更新
        if (Integer.valueOf(newVersion) > Integer.valueOf(currentVersion)) {
            return true;
        } else {
            return false;
        }
    }

    /***
     * 获取当前版本
     * @return
     */
    public static String getCurrentVersion() {
        String currentVersion = "1.0.0";
        PackageManager packageManager = DMApplication.getInstance().getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        try {
            PackageInfo packInfo = packageManager.getPackageInfo(DMApplication.getInstance().getPackageName(), 0);
            currentVersion = packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return currentVersion;
    }

    /**
     * 下载APK
     *
     * @param fileUrl
     * @param destFileDir
     * @param callBack
     */
    public void downLoadAPK(String fileUrl, final String destFileDir, final ReqProgressCallBack callBack) {
        if (!fileUrl.contains("http")) {
            if (fileUrl.startsWith("/")) {
                fileUrl = fileUrl.substring(1);
            }
//            fileUrl = Constant.BASE_URL + fileUrl;
            fileUrl = DMConstant.Config.BASE_URL + "/" + fileUrl;
        }
        //这个是ui线程回调，可直接操作UI
        final UIProgressListener uiProgressResponseListener = new UIProgressListener() {
            @Override
            public void onUIProgress(long bytesRead, long contentLength, boolean done) {
                if (contentLength != -1) {
                    //长度未知的情况下回返回-1
                }
                //ui层回调,设置下载进度
                int progress = (int) ((100 * bytesRead) / contentLength);
                callBack.updateProgress(progress);
            }

            @Override
            public void onUIStart(long bytesRead, long contentLength, boolean done) {
                super.onUIStart(bytesRead, contentLength, done);
                //开始下载
                callBack.startDownLoad();
            }

            @Override
            public void onUIFinish(long bytesRead, long contentLength, boolean done) {
                super.onUIFinish(bytesRead, contentLength, done);
                //开始完成
                installApk(destFileDir);
            }
        };
        //开启文件下载
        DownLoadUtils.downloadAndSaveFile(mContext, fileUrl, destFileDir, uiProgressResponseListener);
    }

    public void cancel(String fileUrl) {
        DownLoadUtils.cancelCallsWithTag(fileUrl);
    }

    /**
     * 安装apk
     */
    private void installApk(String saveFileName) {
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
        mContext.startActivityForResult(intent, CODE_REQUEST);
    }

    public void onActivityResult(DialogFragment dialogFragment, int requestCode, int resultCode, Intent data) {
        if (!(resultCode == Activity.RESULT_OK)) {
            dialogFragment.dismiss();
        }
    }


    public interface ActionInterFace<T> {
        void onFailure(String msg);

        void onConnectFailure(String msg);

        void showNewVersion(T updateBean);

        void showLocalVersion();

        void showMustUpdate(T updateBean);

        void showRequestError(String code, String description);
    }

    public interface ReqProgressCallBack {
        /**
         * 更新进度
         *
         * @param progress
         */
        void updateProgress(int progress);

        /**
         * 开始下载
         */
        void startDownLoad();
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static String getVersionName(Context context) {
        String mVersionName = null;
        try {
            String packageName = context.getPackageName();
            PackageManager manager = context.getPackageManager();
            mVersionName = manager.getPackageInfo(packageName, 0).versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mVersionName;
    }
}
